// 全局工具函数
window.LotteryApp = {
    // 显示Toast消息
    showToast: function(message, type = 'success') {
        // 优先使用页面特定的Toast
        let toastEl = document.getElementById('toastMessage');
        let toastBody = document.getElementById('toastBody');
        
        // 如果页面特定的Toast不存在，使用全局Toast
        if (!toastEl || !toastBody) {
            toastEl = document.getElementById('globalToast');
            toastBody = document.getElementById('globalToastBody');
        }
        
        if (!toastEl || !toastBody) {
            console.error('No toast elements found, using alert');
            alert(message);
            return;
        }
        
        toastBody.textContent = message;
        
        // 重置类名
        toastEl.className = 'toast';
        if (type === 'error') {
            toastEl.classList.add('bg-danger', 'text-white');
        } else if (type === 'warning') {
            toastEl.classList.add('bg-warning', 'text-dark');
        } else {
            toastEl.classList.add('bg-success', 'text-white');
        }
        
        try {
            const toast = new bootstrap.Toast(toastEl);
            toast.show();
        } catch (error) {
            console.error('Error showing toast:', error);
            alert(message);
        }
    },

    // 格式化时间
    formatTime: function(dateString) {
        const date = new Date(dateString);
        return date.toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit', 
            second: '2-digit' 
        });
    },

    // 验证身份证号码格式
    validateIdCard: function(idCard) {
        if (!idCard || idCard.length !== 18) {
            return false;
        }
        
        // 基础格式验证
        const pattern = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
        if (!pattern.test(idCard)) {
            return false;
        }
        
        // 校验码验证
        const codes = "10X98765432";
        const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        let sum = 0;
        
        for (let i = 0; i < 17; i++) {
            sum += parseInt(idCard[i]) * weights[i];
        }
        
        const checkCode = codes[sum % 11];
        return checkCode === idCard[17].toUpperCase();
    },

    // 防抖函数
    debounce: function(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },

    // 节流函数
    throttle: function(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }
};

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 为所有表单添加基础验证
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            // 检查必填字段
            const requiredFields = form.querySelectorAll('[required]');
            let isValid = true;
            
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    field.classList.add('is-invalid');
                    isValid = false;
                } else {
                    field.classList.remove('is-invalid');
                }
            });
            
            if (!isValid) {
                e.preventDefault();
                LotteryApp.showToast('请填写所有必填字段', 'error');
                return false;
            }
        });
    });

    // 身份证输入框特殊处理
    const idCardInputs = document.querySelectorAll('input[name="id_card"]');
    idCardInputs.forEach(input => {
        input.addEventListener('input', function() {
            // 只允许数字和字母X
            this.value = this.value.replace(/[^\dXx]/g, '').toUpperCase();
            
            // 实时验证
            if (this.value.length === 18) {
                if (LotteryApp.validateIdCard(this.value)) {
                    this.classList.remove('is-invalid');
                    this.classList.add('is-valid');
                } else {
                    this.classList.remove('is-valid');
                    this.classList.add('is-invalid');
                }
            } else {
                this.classList.remove('is-valid', 'is-invalid');
            }
        });
    });

    // 姓名输入框处理
    const nameInputs = document.querySelectorAll('input[name="name"]');
    nameInputs.forEach(input => {
        input.addEventListener('input', function() {
            // 移除特殊字符，只保留中文、英文和空格
            this.value = this.value.replace(/[^\u4e00-\u9fa5a-zA-Z\s]/g, '');
        });
    });

    // 添加加载动画效果
    const buttons = document.querySelectorAll('button[type="submit"]');
    buttons.forEach(button => {
        button.addEventListener('click', function() {
            if (this.form && this.form.checkValidity()) {
                this.disabled = true;
                const originalText = this.innerHTML;
                this.innerHTML = '<span class="loading"></span> 处理中...';
                
                // 5秒后恢复按钮状态（防止卡死）
                setTimeout(() => {
                    this.disabled = false;
                    this.innerHTML = originalText;
                }, 5000);
            }
        });
    });

    // 自动刷新功能
    if (window.location.pathname === '/admin') {
        // 管理员页面自动刷新结果
        const autoRefresh = LotteryApp.throttle(() => {
            if (typeof refreshResults === 'function') {
                refreshResults();
            }
        }, 3000);

        // 每3秒刷新一次
        setInterval(autoRefresh, 3000);
    }

    // 键盘快捷键
    document.addEventListener('keydown', function(e) {
        // Ctrl + R 刷新页面
        if (e.ctrlKey && e.key === 'r') {
            e.preventDefault();
            location.reload();
        }
        
        // ESC 关闭模态框和提示
        if (e.key === 'Escape') {
            const toasts = document.querySelectorAll('.toast.show');
            toasts.forEach(toast => {
                const bsToast = bootstrap.Toast.getInstance(toast);
                if (bsToast) bsToast.hide();
            });
        }
    });

    // 添加页面可见性变化处理
    document.addEventListener('visibilitychange', function() {
        if (document.visibilityState === 'visible') {
            // 页面变为可见时，刷新状态
            if (typeof checkLotteryStatus === 'function') {
                checkLotteryStatus();
            }
        }
    });
});

// 网络连接状态检测
window.addEventListener('online', function() {
    LotteryApp.showToast('网络连接已恢复', 'success');
});

window.addEventListener('offline', function() {
    LotteryApp.showToast('网络连接已断开', 'warning');
});

// 错误处理
window.addEventListener('error', function(e) {
    console.error('页面错误:', e.error);
    LotteryApp.showToast('页面出现错误，请刷新重试', 'error');
});

// Promise 错误处理
window.addEventListener('unhandledrejection', function(e) {
    console.error('未处理的Promise错误:', e.reason);
    LotteryApp.showToast('网络请求失败，请检查网络连接', 'error');
});
